import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 刘远望
 * Date: 2025-04-29
 * Time: 20:06
 */
public class HashBuck {

    static class Node {
        public int key;
        public int val;
        public Node next;

        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }

    public Node[] arr = new Node[10];
    public int usedSize;

    public static final double DEFAULT_LOAD_FACTOR = 0.75f;

    //添加数据
    public void push(int key, int val) {
        int index = key % arr.length;
        Node cur = arr[index];
        while (cur != null) {
            if(cur.key == key) {
                cur.val = val;
                return;
            }
            cur = cur.next;
        }
        //没有在当前的链表中找到该节点
        Node node = new Node(key, val);
        //头插法
        node.next = arr[index];
        arr[index] = node;
        usedSize++;
        //扩容
        if(doLoadFactor() >= DEFAULT_LOAD_FACTOR) {
            resize();
        }
    }

    private void resize() {
        //arr = Arrays.copyOf(arr, 2 * arr.length);//错误的写法
        Node[] newArr = new Node[arr.length * 2];
        for (int i = 0; i < arr.length; i++) {
            Node cur = arr[i];
            while (cur != null) {
                int newIndex = cur.key % newArr.length;
                Node curN = cur.next;
                cur.next = newArr[newIndex];
                newArr[newIndex] = cur;
                cur = curN;
            }
        }
        arr = newArr;
    }

    private double doLoadFactor() {
        return usedSize * 1.0 / arr.length;
    }

    //获得值
    public int getVal(int key) {
        int index = key % arr.length;
        Node cur = arr[index];
        while (cur != null) {
            if(cur.key == key) {
                return cur.val;
            }
        }
        return -1;
    }
}
